<%@page import="java.sql.*"%>
<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="error.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>分页显示成语</title>
<style type="text/css">
.kuang{ width: 1000px; margin: auto;}
.nav{ margin-bottom: 10px;}
.count{ border: 3px solid red; display: flex;}
.lan{ border: 1px solid gray; flex-grow: 1; margin: 20px; padding: 10px;}
p{ margin: 0px; padding: 5px;}
h1{ font-size: 50px; text-align: center;}
a{ color: gray; text-decoration: none;}
a:hover{ color: red;}
b{ color: red;}
</style>
</head>

<body>
<%
out.println("<h1>中国成语大全</h1>");

out.println("<div class='kuang'>");

out.println("\t<div class='nav'>");
//out.print(System.getProperty("catalina.base"));
String url="jdbc:mysql://localhost:3306/db?serverTimezone=PRC";
//(1)加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//(2)创建连接
Connection cn = DriverManager.getConnection(url,"root","12qwas");
//(3)创建sql插入语句并设定参数的值
PreparedStatement ps = cn.prepareStatement("select count(*) from chengyu");
ResultSet rs = ps.executeQuery();
rs.next();
int cyshu=rs.getInt(1);//成语数
int lans=5;//栏数
int lancys=10;//每栏成语数
int pagecys=lans*lancys;//每页成语数

int maxPage=cyshu/pagecys+(cyshu%pagecys==0?0:1);
int n=4;
String sym=request.getParameter("page");
if(sym==null)sym="1";
int iym=Integer.parseInt(sym);
if(iym<1)iym=1;
else if(iym>maxPage)iym=maxPage;
//out.print("当前页码："+iym);
int begin=iym-n;
int end=iym+n;
if(begin<1){
	begin=1;
	end=2*n+1;
	if(end>maxPage)end=maxPage;
}else if(end>maxPage){
	end=maxPage;
	begin=maxPage-2*n;
	if(begin<1)begin=1;
}
for(int i=begin;i<=end;++i){
	if(i==iym)out.println("\t\t<b>"+i+"</b>");
	else out.println("\t\t<a href='?page="+i+"'>"+i+"</a>");
}
out.println("\t</div>");

out.println("\t<div class='count'>");
ps = cn.prepareStatement("select cy from chengyu limit ?,?");
ps.setInt(1, (iym-1)*pagecys);
ps.setInt(2, pagecys);
rs = ps.executeQuery();
for(int i=1;i<=lans;++i){
	out.println("\t\t<div class='lan'>");
	for(int j=1;j<=lancys;++j){
		if(rs.next())out.println("\t\t\t<p>"+rs.getString(1)+"<p>");
		else out.println("\t\t\t<p>　　　　<p>");
	}
	out.println("\t\t</div>");
}
out.println("\t</div>");

out.print("</div>");
rs.close();
ps.close();
cn.close();
%>
</body>
</html>